//package com.itheima.tlias84.filter;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.itheima.tlias84.dao.entity.Emp;
//import com.itheima.tlias84.dao.mapper.EmpMapper;
//import com.itheima.tlias84.utils.JwtUtil;
//import com.itheima.tlias84.utils.ResultUtil;
//import jakarta.annotation.Resource;
//import jakarta.servlet.*;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.util.Objects;
//
///**
// * 登录过滤器，进行登录token拦截
// */
//@Slf4j
//@Component
//public class LoginFilter implements Filter {
//
//    @Resource
//    EmpMapper empMapper;
//
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
//    }
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        log.info("登录过滤器执行了");
//        //参数向下转型
//        HttpServletRequest req = (HttpServletRequest) servletRequest;
//        HttpServletResponse resp = (HttpServletResponse) servletResponse;
//        //放行登录接口
//        String requestURI = req.getRequestURI();
//        if (requestURI.contains("login")) {
//            filterChain.doFilter(servletRequest, servletResponse);
//            return;
//        }
//
//        //获取请求头中的Token
//        String token = req.getHeader("token");
//        //判断是否有token
//        if (Objects.isNull(token)) {
//            writeErrorResp(resp, "请先登录");
//            return;
//        }
//        //判断token是否合法
//        try {
//            JSONObject object = JwtUtil.verifyToken(token);
//            Emp emp = empMapper.selectByUsername(object.getString("username"));
//            if (Objects.isNull(emp) || !emp.getPassword().equals(object.getString("password"))) {
//                writeErrorResp(resp, "token不合法或已过期");
//                return;
//            }
//        } catch (Exception e) {
//            writeErrorResp(resp, "token不合法或已过期");
//            return;
//        }
//
//
//        //过滤器对象执行完过滤逻辑后放行Http请求，把request和response对象传递给下一个过滤器或者Controller(Servlet)
//        filterChain.doFilter(servletRequest, servletResponse);
//        log.info("过滤完成");
//    }
//
//    private static void writeErrorResp(HttpServletResponse resp, String msg) throws IOException {
//        resp.setCharacterEncoding("UTF-8");
//        //设置响应状态码
//        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//
//        PrintWriter writer = resp.getWriter();
//        ResultUtil failure = ResultUtil.failure(msg);
//        writer.write(JSONObject.toJSONString(failure));
//    }
//
//    @Override
//    public void destroy() {
//        Filter.super.destroy();
//    }
//}
